<template>
  <div class="public-sea-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="left-actions">
            <el-checkbox v-model="selectAll" @change="toggleSelectAll">已选中 {{ selectedRowKeys.length }} 项</el-checkbox>
            <el-button size="small" @click="handleGrab">抓取客户</el-button>
            <el-button size="small" @click="handleCall">轮呼</el-button>
            <el-button size="small" @click="handleAddToFollow">添加跟进客户</el-button>
            <el-button size="small" @click="handleAssign">分配客户</el-button>
          </div>
          <div class="right-actions">
            <el-button type="primary" size="small" @click="handleCreate">新建</el-button>
            <el-dropdown>
              <el-button size="small">导入</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleImport('file')">导入文件</el-dropdown-item>
                  <el-dropdown-item @click="handleImport('excel')">导入Excel</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 筛选/搜索区域 -->
      <div class="filter-bar">
        <el-input v-model="keyword" placeholder="请输入搜索客户" :prefix-icon="Search" clearable style="width: 240px" @keyup.enter="fetchList" />
        <el-select v-model="advancedFilter" placeholder="高级筛选" clearable style="width: 140px">
          <el-option label="潜在客户" value="潜在客户" />
          <el-option label="意向客户" value="意向客户" />
          <el-option label="需求客户" value="需求客户" />
        </el-select>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 260px" />
        <el-button type="primary" :icon="Search" @click="fetchList">筛选</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>

      <!-- 表格数据展示 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名/头像" min-width="120">
          <template #default="scope">
            <div class="user-info">
              <el-avatar :size="36" :src="scope.row.avatar || defaultAvatar" />
              <span class="user-name">{{ scope.row.name || '未命名' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="type" label="客户类型" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.type" :type="mapTypeToTag(scope.row.type).type">{{ mapTypeToTag(scope.row.type).text }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="客户来源" min-width="100" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column prop="lastFollowTime" label="最后跟进时间" min-width="160" />
        <el-table-column prop="callStatus" label="轮呼状态" min-width="100" v-if="false">
          <template #default="scope">
            <el-tag v-if="scope.row.callStatus" :type="getStatusType(scope.row.callStatus)">{{ scope.row.callStatus }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" text @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" text type="primary" @click="handleGrabSingle(scope.row)">抓取</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 表格数据相关
const tableData = ref<any[]>([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const selectedRowKeys = ref<number[]>([])
const selectAll = ref(false)
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 筛选条件
const keyword = ref('')
const advancedFilter = ref('')
const dateRange = ref<[Date, Date] | null>(null)

// 初始化
onMounted(() => {
  fetchList()
})

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    // 构建查询参数，与资源库保持一致
    const params = {
      page: page.value,
      page_size: pageSize.value,
      keyword: keyword.value || undefined,
      // 根据需要添加其他筛选条件
      type: advancedFilter.value ? {
        '潜在客户': 1,
        '意向客户': 2,
        '需求客户': 3
      }[advancedFilter.value] : undefined
    }
    
    // 发送请求到后端接口，使用与资源库相同的接口
    const response = await axios.get('/customers/list', { params })
    
    if (response.data.data && Array.isArray(response.data.data.customers)) {
      tableData.value = response.data.data.customers
      // 尝试多种可能的total值位置，确保分页功能正常
      total.value = response.data.total || response.data.data.total || tableData.value.length
    } else {
      // 兜底处理，确保tableData始终是数组
      console.warn('API响应数据结构不符合预期', response.data)
      tableData.value = []
      total.value = 0
    }
    
    console.log('获取客户列表成功，共', total.value, '条数据')
  } catch (error: any) {
    console.error('获取客户列表失败:', error)
    // 区分网络错误和服务器错误
    if (error.response) {
      const errorMsg = error.response.data?.message || `获取客户列表失败: ${error.response.status}`
      ElMessage.error(errorMsg)
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 选择变化处理
const handleSelectionChange = (selection: any[]) => {
  selectedRowKeys.value = selection.map(item => item.id)
  selectAll.value = selection.length > 0 && selection.length === tableData.value.length
}

// 全选处理
const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedRowKeys.value = tableData.value.map(item => item.id)
  } else {
    selectedRowKeys.value = []
  }
}

// 分页变化处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchList()
}

const handleCurrentChange = (val: number) => {
  page.value = val
  fetchList()
}

// 重置筛选
const resetFilters = () => {
  keyword.value = ''
  advancedFilter.value = ''
  dateRange.value = null
  fetchList()
}

// 将客户类型数字转换为文本
const mapTypeToTag = (type: number) => {
  switch (type) {
    case 1:
      return { type: 'success', text: '潜在客户' }
    case 2:
      return { type: 'warning', text: '意向客户' }
    case 3:
      return { type: 'info', text: '需求客户' }
    case 4:
      return { type: 'primary', text: '签单客户' }
    case 5:
      return { type: 'danger', text: '放款客户' }
    default:
      return { type: 'info', text: '未知类型' }
  }
}

// 获取状态类型
const getStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    1: 'info',
    2: 'warning',
    3: 'success'
  }
  return statusMap[status] || 'default'
}

// 批量抓取客户
const handleGrab = async () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请选择要抓取的客户')
    return
  }
  
  try {
    const response = await axios.post('/customers/grab', {
      ids: selectedRowKeys.value
    })
    
    if (response.data && response.data.code === 0) {
      ElMessage.success('抓取成功')
      selectedRowKeys.value = []
      fetchList()
    } else {
      ElMessage.error(response.data?.message || '抓取失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 单个抓取客户
const handleGrabSingle = async (row: any) => {
  try {
    const response = await axios.post('/customers/grab', {
      ids: [row.id]
    })
    
    if (response.data && response.data.code === 0) {
      ElMessage.success('抓取成功')
      fetchList()
    } else {
      ElMessage.error(response.data?.message || '抓取失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 轮呼
const handleCall = () => {
  ElMessage.info('轮呼功能开发中')
}

// 添加跟进客户
const handleAddToFollow = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请选择要添加的客户')
    return
  }
  ElMessage.info('添加跟进客户功能开发中')
}

// 分配客户
const handleAssign = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请选择要分配的客户')
    return
  }
  ElMessage.info('分配客户功能开发中')
}

// 新建
const handleCreate = () => {
  ElMessage.info('新建客户功能开发中')
}

// 导入
const handleImport = (type: string) => {
  ElMessage.info(`导入${type}功能开发中`)
}

// 查看详情
const handleView = (row: any) => {
  // 跳转到详情页
  window.location.href = `/customers/detail/${row.id}`
}
</script>

<style scoped>
.public-sea-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.right-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 15px;
  margin: 20px 0;
  flex-wrap: wrap;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>